package utils.text;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 替换文本中的字符串，全文本替换可替换段落
 * 
 * @author:张三石
 * @since:2021年9月14日 上午9:16:42
 */
public class ReplaceStrOnParagraph {
	// 计数
	public static int count = 0;
	public static String separator = System.getProperty("line.separator");//平台换行!
	public static String encoding = "UTF-8";

	public static void main(String[] args) {

		File file = new File("C:\\Users\\o.o\\Desktop\\core");
		new ReplaceStrOnParagraph().loop(file);
		System.out.println(count);
	}

	void loop(File file) {

		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (File obj : files) {
				loop(obj);
			}
		} else {
			setText(file, "目标字符串", "替换字符串");
		}
	}

	public static void setText(File file, String target, String replacement) {//修改

		Long filelength = file.length();
		byte[] filebytes = new byte[filelength.intValue()];

		try (FileInputStream fis = new FileInputStream(file);) {
			fis.read(filebytes);

			String fileContent = new String(filebytes);

			if (fileContent.contains(target)) {
				count++;
				fileContent = fileContent.replace(target, replacement);
			}

			try (FileOutputStream fos = new FileOutputStream(file)) {
				fos.write(fileContent.getBytes());
				fos.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}